package userShareModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"time"
)

type createShareFileRequest struct {
	FileId    model.SnowflakeIdType `json:"fileId" binding:"required"`
	ValidType uint8                 `json:"validType" binding:"required"`
	Code      string                `json:"code"`
}

func (UserShareModuleApi) CreateShareFile(c *gin.Context) {
	var req createShareFileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Errorf("bind json err:%v", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	if req.Code == "" {
		req.Code = utils.RandomString(5)
	} else {
		if len(req.Code) != 5 {
			res.FailWithCode(res.PARAM_ERR, c)
			return
		}
	}
	userId := utils.GetUserId(c)
	if userId == 0 {
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	tx := global.DB.Begin()
	now := time.Now().Unix()
	expireTime, err := enums.CalculateExpirationTime(req.ValidType)
	if err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	s := model.ShareModel{
		ShareID:       utils.RandomString(6),
		FileID:        req.FileId,
		UserID:        userId,
		ValidType:     req.ValidType,
		ExpireTime:    expireTime,
		ShareTime:     now,
		SharePassWord: req.Code,
	}
	if Err := tx.Create(&s).Error; Err != nil {
		tx.Rollback()
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if Err := tx.Commit().Error; Err != nil {
		tx.Rollback()
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(s, c)
}
